package org.example.project.common.error.handle;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.example.project.common.util.AspectLogUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 简单注解日志切面实现
 * <p>
 * 显示使用@Log注解，记录请求信息
 *
 * @author theskyzero
 * @see com.yundasys.vienna.common.web.annotation.Log
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    @Value("${yundasys.vienna.common.annotation-log.enable:true}")
    boolean enable;

    @Pointcut("@annotation(com.yundasys.vienna.common.web.annotation.Log)")
    public void logPointcut() {
    }

    @AfterReturning(pointcut = "logPointcut()", returning = "result")
    public void logAround(JoinPoint joinPoint, Object result) throws Throwable {
        if (isEnable() && log.isInfoEnabled()) {
            log.info(AspectLogUtils.buildLog(joinPoint, result).toString());
        }
    }

    /**
     * 配置异常通知
     *
     * @param joinPoint join point for advice
     * @param e         exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        // 记录日志，异常会继续抛出
        if (isEnable() && log.isErrorEnabled()) {
            log.error(AspectLogUtils.buildLog(joinPoint, e).toString());
        }
    }

    public boolean isEnable() {
        return enable;
    }
}
